﻿using System;
using DeferredPropertyConstraints.Model;
using NUnit.Framework;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;

namespace DeferredPropertyConstraints
{
  public class Program
  {
    [Test]
    public static void Main()
    {
      // Loading domain configuration section with name "Default".
      var domainConfiguration = DomainConfiguration.Load("Default");
      var domain = Domain.Build(domainConfiguration);

      using (var session = domain.OpenSession()) {

        // Session.Validate() is automatically called on transaction commit
        try {
          using (var t = session.OpenTransaction()) {
          
            var entity = new MyEntity(session);
            // Setting invalid value
            entity.Text = string.Empty;

            t.Complete();
          } // <-- Here Session.Validate() is called
        }
        catch (InvalidOperationException exception) {
          Console.WriteLine(exception);
        }

        // Alternatively, Session.Validate() can be called manually anytime
        using (var t = session.OpenTransaction()) {
          
          var entity = new MyEntity(session);
          // Setting invalid value
          entity.Text = string.Empty;

          try {
            // Calling session.Validate() manually will throw the exception
            session.Validate();
            t.Complete();
          }
          catch (Xtensive.Core.AggregateException exception) {
            Console.WriteLine(exception);
          }
        }
      }
    }
  }
}
